<template>
  <div class="app-container">
    <el-dialog
      title="列设置"
      :visible.sync="dialogVisible"
      width="75%"
    >
      <span>
        <Button type="warning" @click="addColumnField">新增</Button>
        <Row style="margin-top: 5px">
          <Col span="12" class="no-padding border-bottom border-right boder-margin">

            <el-table
              ref="leftTable"
              :data="tableData"
              size="mini"
              style="width: 100%"
              border
            >
              <el-table-column
                type="selection"
                width="55"
              />
              <el-table-column
                fixed
                prop="columnKey"
                label="字段"
              />

              <el-table-column
                prop="description"
                label="描述"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.description" />
                </template>

              </el-table-column>
              <el-table-column
                prop="dataType"
                label="类型"
              />
            </el-table>

          </Col>
          <Col span="10" class="border-right border" style="padding-left: 10px;margin-left: 10px">

            <el-table
              ref="rightTable"
              :data="existData"
              size="mini"
              border
            >
              <el-table-column
                type="selection"
                width="55"
              />
              <el-table-column
                fixed
                prop="columnKey"
                label="字段"
              />

              <el-table-column
                prop="description"
                label="描述"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.description" />
                </template>

              </el-table-column>
              <el-table-column
                prop="dataType"
                label="类型"
              >
                <template slot-scope="scope">
                  <Button type="success" @click="removeRight(scope.$index)">删除</Button>
                </template>

              </el-table-column>
            </el-table>
          <!--          <Table border highlight-row ref="showTable" style="padding-top: 10px"-->
          <!--                 height="450"-->
          <!--                 :columns="showTableColumns" :data="showTableData"></Table>-->
          </Col>
        </Row>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmField">确 定</el-button>
      </span>
    </el-dialog>
    <Row>
      <Col span="24" />
      <Card>
        <p slot="title">对话框</p>

        <Form ref="formInline" :model="formInline" :label-width="90" :rules="ruleValidate">
          <FormItem prop="name" label="名称">

            <Input v-model="formInline.name" type="text" class="input_w" />
          </FormItem>

          <FormItem prop="alias" label="简称">
            <Input v-model="formInline.alias" type="text" class="input_w" />
          </FormItem>

          <FormItem prop="style" label="样式">
            <RadioGroup v-model="formInline.style" class="input_w">
              <Radio label="1">
                <span>列表</span>
              </Radio>
              <Radio label="0">
                <span>树形</span>
              </Radio>
            </RadioGroup>

          </FormItem>
          <FormItem prop="system" label="系统内置">
            <RadioGroup v-model="formInline.system">
              <Radio label="true">
                <span>是</span>
              </Radio>
              <Radio label="false">
                <span>否</span>
              </Radio>
            </RadioGroup>

          </FormItem>
          <FormItem prop="width" label="宽度">
            <Input v-model="formInline.width" type="text" class="input_w" />
          </FormItem>
          <FormItem prop="height" label="高度">
            <Input v-model="formInline.height" type="text" class="input_w" />
          </FormItem>
          <FormItem prop="needPage" label="分页">
            <RadioGroup v-model="formInline.needPage">
              <Radio label="true">
                <span>是</span>
              </Radio>
              <Radio label="false">
                <span>否</span>
              </Radio>
            </RadioGroup>

          </FormItem>

          <FormItem prop="selectNum" label="单选多选">
            <RadioGroup v-model="formInline.selectNum">
              <Radio label="true">
                <span>是</span>
              </Radio>
              <Radio label="false">
                <span>否</span>
              </Radio>
            </RadioGroup>

          </FormItem>
          <FormItem prop="dsType" label="数据来源">
            <RadioGroup v-model="formInline.dsType" :disabled="edit" @on-change="changeselectNum">
              <Radio label="dataSource" :disabled="edit">
                <span>数据源</span>
              </Radio>
              <Radio label="restful" :disabled="edit">
                <span>REST接口</span>
              </Radio>
            </RadioGroup>

          </FormItem>
          <Tabs :value="formInline.tableName" :active-name="formInline.tableName">
            <TabPane label="数据源" name="dataSource" :disabled="formInline.dataSourceHide">

              <el-alert class="no-print" title="首先在查询表输入框中输入表信息，然后点击查询。存在的表数据会自动填充到“选择表&quot;下拉框。" show-icon type="warning" style="margin-bottom:10px" />

              <FormItem label="数据源" prop="dsAlias">
                <Select v-model="formInline.dsAlias" class="input_w" :disabled="edit">
                  <Option value="LOCA">本地数据源</Option>
                </Select>
              </FormItem>
              <FormItem label="查询表" prop="queryObjectName" :disabled="edit">
                <Input v-model="formInline.queryObjectName" type="text" class="input_w" :disabled="edit" />
                <Button type="primary" style="margin-bottom: 2px;margin-right: 15px;" :disabled="edit" @click="add">查询
                </Button>
              </FormItem>
              <FormItem prop="groupName" label="选择表">

                <div style="display: block; ">
                  <treeselect
                    v-model="formInline.objName"
                    class="input_w"
                    :disabled="edit"
                    :normalizer="normalizer"
                    :multiple="false"
                    placeholder="请选择"
                    :options="categoryData"

                    @select="selectTree"
                    @input="clearOnSelect"
                  />
                </div>
                <div style="display: block;">
                  <Button
                    type="primary"
                    style="margin-bottom: 2px;margin-right: 15px;    margin-left: 30.5%;
    margin-top: -70px;"
                    :disabled="edit"
                    @click="addColumn"
                  >设置列
                  </Button>
                </div>

              </FormItem>
            </TabPane>
            <TabPane label="REST接口" name="restful" :disabled="formInline.restfulHide">
              <FormItem prop="url" label="请求地址">
                <Input v-model="formInline.url" type="text" class="input_w" />
              </FormItem>

              <FormItem prop="selectNum" label="请求类型">
                <RadioGroup v-model="formInline.requestType">
                  <Radio label="POST">
                    <span>POST</span>
                  </Radio>
                  <Radio label="GET">
                    <span>GET</span>
                  </Radio>
                </RadioGroup>

              </FormItem>

              <FormItem prop="url" label="页号（key)">
                <Input v-model="formInline.pageKey" type="text" class="input_w" />
              </FormItem>

              <FormItem prop="url" label="分页大小(key)">
                <Input v-model="formInline.pageSizeKey" type="text" class="input_w" />
              </FormItem>
              <FormItem prop="url" label="总条数（key)">
                <Input v-model="formInline.totalKey" type="text" class="input_w" />
              </FormItem>
              <FormItem prop="url" label="列表(key)">
                <Input v-model="formInline.listKey" type="text" class="input_w" />
              </FormItem>

            </TabPane>
          </Tabs>

        </Form>
        <el-button type="primary" :loading="loading" @click="save">保存</el-button>

      </Card>
      </Col>

    </Row>
  </div>

</template>

<script>
import { getTaskData } from '@/api/analy'
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// eslint-disable-next-line no-unused-vars
import busTable from '@/views/common/busTable'
import metadataDialog from '@/views/common/metadataDialog'
import {
  businessTableCreate,
  customDialogMetadataInfo,
  businessTableMetadataInfo,
  customDialogSave,
  customDialogGet
} from '@/api/form'
import { isColumnKey, attrLengthValidator } from '@/utils/validate'

export default {
  name: 'Task',
  // eslint-disable-next-line vue/no-unused-components
  components: { Treeselect, metadataDialog },

  data() {
    return {
      dialogVisible: false,
      loading: false,

      busChildShow: false,
      edit: true,
      ruleForm: {
        tableData: []
      },
      rules: {
        description: [{ required: true, message: '  ', trigger: 'blur' }],
        decimalLength: [{ required: true, message: '  ', trigger: 'blur' }],
        attrLength: [{
          validator: attrLengthValidator,
          trigger: 'blur'
        }],
        columnKey: [{ required: true, message: '  ', trigger: 'blur' }, { validator: isColumnKey, trigger: 'blur' }]
      },

      options: [{
        value: 'oneToOne',
        label: '一对一'
      }, {
        value: 'oneToMany',
        label: '一对多'
      }],
      tableFormRules: {
        description: { type: 'string', required: true, message: '必填字段', trigger: 'change' }
      },
      ruleValidate: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        alias: [
          { required: true, message: '请输入简称', trigger: 'blur' }
        ],
        style: [
          { required: true, message: '请选择样式', trigger: 'blur' }
        ],
        system: [
          { required: true, message: '请选择系统内置', trigger: 'blur' }
        ]
      },
      // define the default value
      value: '',
      formatOptions: [{
        value: 'yyyy-MM-dd HH:mm:ss',
        label: 'yyyy-MM-dd HH:mm:ss'
      }, {
        value: 'yyyy-MM-dd',
        label: 'yyyy-MM-dd'
      }, {
        value: 'HH:mm:ss',
        label: 'HH:mm:ss'
      }],
      formatValue: 'yyyy-MM-dd HH:mm:ss',
      formInline: {
        style: '0',
        width: '800',
        height: '600',
        selectNum: 'true',
        tableName: 'dataSource',
        dataSourceHide: false,
        restfulHide: true,
        needPage: 'true',
        system: 'true',
        dsType: 'dataSource',
        dsAlias: 'LOCA',
        formKey: '',
        url: '',
        requestType: 'POST',
        pageKey: 'page',
        pageSizeKey: 'pageSize',
        totalKey: 'total',
        listKey: 'rows',
        queryObjectName: '',
        groupId: '',
        groupName: null,
        id: ''
      },

      tableData: [],
      tableColumns: [
        {
          type: 'selection',
          width: 70,
          align: 'center'
        },

        {
          title: '名称',
          key: 'modelName'
        },
        {
          title: '表名',
          key: 'tableName'
        },
        {
          title: '描述',
          key: 'description'
        },
        {
          title: '分类',
          key: 'groupName'
        },
        {
          title: '类型',
          key: 'type'
        }
      ],
      tableHeight: 450,
      queryDate: [],
      total: 0,
      chartVisible: false,
      chartData: {},
      sellerId: 0,
      shopName: [],
      queryForm: {
        groupId: '',
        page: 0,
        limit: 10
      },
      categoryData: [],
      existTableData: [],
      existData: [],
      mainTable: null,
      childTable: null
    }
  },
  mount() {
    this.getData()
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop
  },
  created() {
    var query = this.$route.query
    // eslint-disable-next-line no-unused-vars
    var operate = query.operate
    var edit = query.edit
    if (edit) {
      this.edit = JSON.parse(edit)
    }

    if (query.id) {
      this.formInline.id = query.id
      this.initData(edit)
    } else {
      this.formInline.dataSourceHide = false
      this.formInline.restfulHide = true
      this.edit = false
    }
  },

  methods: {
    confirmField: function() {
      // eslint-disable-next-line no-unused-vars
      var checkData = this.existData
      this.dialogVisible = false
    },
    removeRight: function(index) {
      this.existData.splice(index, 1)
    },
    addColumnField: function() {
      var checkData = this.$refs.leftTable.selection

      this.existData = checkData
    },
    addColumn: function() {
      if (this.formInline.objName) {
        this.dialogVisible = true
        businessTableMetadataInfo(this.formInline.objName).then((response) => {
          // eslint-disable-next-line eqeqeq
          if (response.code == 0) {
            this.tableData = response.data
          }
        })
      } else {
        this.$message({ 'duration': 800, message: '请先选择列', type: 'warning', customClass: 'zZindex' })
      }
    },
    changeselectNum: function(data) {
      this.formInline.tableName = data
      // eslint-disable-next-line eqeqeq
      if (data == 'dataSource') {
        this.formInline.dataSourceHide = false
        this.formInline.restfulHide = true
      } else {
        this.formInline.dataSourceHide = true
        this.formInline.restfulHide = false
      }
    },
    operateDisabled: function(data) {
      // eslint-disable-next-line eqeqeq
      if (this.formInline.type == 'inner' && (this.formInline.createdTable == 'false' || this.formInline.createdTable == false)) {
        return false
      // eslint-disable-next-line eqeqeq
      } else if (this.formInline.type == 'inner' && (this.formInline.createdTable == 'true' || this.formInline.createdTable == true)) {
        if (data.id) {
          return true
        } else {
          return false
        }
      }
      return true
    },
    operateShowExistdData: function(data) {
      // eslint-disable-next-line eqeqeq
      if (this.formInline.type == 'external') {
        return true
      } else {
        return false
      }
    },
    operateDisabledDelBtn: function(data) {
      // eslint-disable-next-line eqeqeq
      if (this.formInline.type == 'inner' && (this.formInline.createdTable == 'false' || this.formInline.createdTable == false)) {
        return true
      // eslint-disable-next-line eqeqeq
      } else if (this.formInline.type == 'inner' && (this.formInline.createdTable == 'true' || this.formInline.createdTable == true)) {
        if (data.id) {
          return false
        } else {
          return true
        }
      }
      return false
    },
    createTable: function() {
      businessTableCreate(this.formInline.id).then((response) => {
        // eslint-disable-next-line eqeqeq
        if (response.code == 0) {
          this.$message({ 'duration': 800, message: '操作成功', type: 'warning', customClass: 'zZindex' })

          this.initData()
        }
      })
    },
    initData: function(edit) {
      customDialogGet(this.formInline.id).then((response) => {
        // eslint-disable-next-line eqeqeq
        if (response.code == 0) {
          var data = response.data
          this.formInline = data
          this.formInline.needPage = data.needPage.toString()
          this.formInline.selectNum = data.selectNum.toString()
          this.formInline.system = data.system.toString()
          // eslint-disable-next-line eqeqeq
          if (data.dsType == 'dataSource') {
            this.existData = JSON.parse(data.resultFieldStr)
          }
          if (data.objName) {
            this.formInline.queryObjectName = data.objName
            this.add()
          }
          if (edit) {
            this.formInline.dataSourceHide = true
            this.formInline.restfulHide = true
          }
        }
      })
    },
    selectTree: function(node, instanceId) {
      this.formInline.groupId = node.id
      this.formInline.groupName = node.title
    },

    clearOnSelect: function(node, instanceId) {
      if (!node) {
        this.formInline.groupId = ''
        this.formInline.groupName = null
      }
    },
    clearExistTableOnSelect: function(node, instanceId) {
      if (!node) {
        this.formInline.tableName = null
      }
    },
    validateFormInline: function() {
      this.$nextTick(() => {
        this.$refs['formInline'].validate((valid) => {

        })
      })
    },
    save: function() {
      this.$refs['formInline'].validate((valid) => {
        if (valid) {
          this.loading = true

          // eslint-disable-next-line no-unused-vars
          var data = {}
          var formData = this.formInline
          const obj = JSON.parse(JSON.stringify(this.formInline))
          // eslint-disable-next-line eqeqeq
          if (formData.dsType == 'dataSource') {
            obj['resultFieldStr'] = JSON.stringify(this.existData)
          }

          customDialogSave(obj).then((response) => {
            // eslint-disable-next-line eqeqeq
            if (response.code == 0) {
              // 调用全局挂载的方法
              this.$store.dispatch('tagsView/delView', this.$route)
              // 返回上一步路由
              this.$router.go(-1)
            } else {
              this.$message({ 'duration': '800', message: response.msg, type: 'success', customClass: 'zZindex' })
            }
            this.loading = false
          })
        } else {
          return
        }
      })
    },
    selectDataTypeChanged: function(value, index) {
      this.ruleForm.tableData[index].type = value
    },

    delField: function(index) {
      this.ruleForm.tableData.splice(index, 1)
      this.$message({ 'duration': 800, message: '操作成功', type: 'warning', customClass: 'zZindex' })
    },
    disabledDelBtn: function(row) {
      for (var i = 0; i < this.existData.length; i++) {
        if (row === this.existData[i]) {
          return true
        }
      }
      return false
    },
    handleSubmit: function(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$Message.success('Success!')
        } else {
          this.$Message.error('Fail!')
        }
      })
    },
    add: function() {
      if (this.formInline.queryObjectName) {
        customDialogMetadataInfo(this.formInline.queryObjectName).then((response) => {
          // eslint-disable-next-line eqeqeq
          if (response.code == 0) {
            this.categoryData = response.data
          }
        })
      }
    },
    queryFormCreateTime: function(e) {
      this.queryForm.createTime = e
    },
    refreshTask: function(data) {
      // eslint-disable-next-line eqeqeq
      if (data[0].parentId == '-1') {
        this.queryForm.typeKey = ''
      } else {
        this.queryForm.typeKey = data[0].typeKey
      }
      this.queryForm.createTime = ''
      this.queryDate = []
      this.queryForm.whereSql = ''
      this.getData()
    },
    queryMethod: function() {
      // eslint-disable-next-line no-unused-vars
      var name = this.queryForm.name
      var whereSql = ''
      var createTime = this.queryForm.createTime
      if (createTime) {
        if (createTime[0]) {
          whereSql = "  CREATE_TIME_  between '" + createTime[0] + "' and " + "'" + createTime[1] + "'"
        }
      }
      this.queryForm.whereSql = whereSql
      getTaskData(this.queryForm).then((response) => {
        this.tableData = response.data
        if (response.count.length > 0) {
          this.total = parseInt(response.count)
        } else {
          this.total = 0
        }
      })
    },
    // 后台返回的数据如果和VueTreeselect要求的数据结构不同，需要进行转换
    normalizer(node) {
      // 去掉children=[]的children属性
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.tableName,
        label: node.tableName + '(' + node.tableComment + ')',
        children: node.children
      }
    },
    existTableNormalizer(node) {
      return {
        id: node.tableName,
        label: node.tableComment,
        children: node.children
      }
    },
    getData: function() {
    },
    handleCurrentChange(val) {
      this.queryForm.page = val
      this.getData()
    },
    handleClick(data) {
      this.$router.push({ name: 'handleRunTask', query: { t: new Date().getTime(), 'taskId': data.id }})
    },
    search() {
      this.queryForm.page = 0
      this.queryMethod()
    },
    reset() {
      this.queryForm.name = ''
      this.queryForm.createTime = ''
      this.queryForm.whereSql = ''
      this.queryDate = []
      this.getData()
    }

  }

}

</script>
<style lang="scss">
  .task-card {
    margin-top: 10px;
  }

  .input_w {
    width: 30% !important;
  }

  .cell {
    max-height: 54px !important;
    overflow: auto !important;
  }

</style>
